﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Microsoft.Synchronization;
using System.Threading;
using System.Windows.Media.Animation;
using DBSync.Util;
using DbSync;
using System.Configuration;

namespace DBSync.wpfPage
{
    /// <summary>
    /// Interaction logic for HomePage.xaml
    /// </summary>
    public partial class HomePage : Page
    {
        public static HomePage instance;

        private static DrCarDriveDataCacheSyncAgent drCarAgent;
        private static PHRDataCacheSyncAgent phrAgent;
        public HomePage()
        {
            InitializeComponent();
        }

        public static HomePage Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new HomePage();
                }

                return instance;
            }
        }

        private void btnSyncStart_Click(object sender, RoutedEventArgs e)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = config.AppSettings.Settings;
            string host = settings[SyncKeys.HOST].Value;
            bool hasInternet = InternetDetector.detectInternetConnection(host);
            if (hasInternet)
            {
                if (chkPHR.IsChecked == true)
                {
                    try
                    {
                        spPHRProgress.Visibility = System.Windows.Visibility.Visible;
                        Thread t = new Thread(runPHRSynchronization);
                        t.SetApartmentState(ApartmentState.STA);
                        t.Start();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                if (chkDRCD.IsChecked == true)
                {
                    try
                    {
                        spDRCDProgress.Visibility = System.Windows.Visibility.Visible;
                        Thread t = new Thread(runDRDCSynchronization);
                        t.SetApartmentState(ApartmentState.STA);
                        t.Start();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            else
            {
                MSGWindow msg = new MSGWindow(Messages.TTL_NO_INTERNET, Messages.MSG_NO_INTERNET);
                msg.ShowDialog();
            }
        }

        public void runPHRSynchronization()
        {
            try
            {
                phrAgent = new PHRDataCacheSyncAgent();
                phrAgent.SessionProgress += phrAgent_SessionProgress;
                phrAgent.Synchronize();
            }
            catch (Exception ex)
            {
                //MSGWindow errorMsg = new MSGWindow("Connection Failed", "Remote connection failed, Please try again");
                MSGWindow errorMsg = new MSGWindow("Connection Failed", ex.Message);
                
                errorMsg.ShowDialog();
            }
        }

        public void runDRDCSynchronization()
        {
            try
            {
                drCarAgent = new DrCarDriveDataCacheSyncAgent();
                drCarAgent.SessionProgress += new EventHandler<SessionProgressEventArgs>(drCarAgent_SessionProgress);
                drCarAgent.Synchronize();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //MSGWindow errorMsg = new MSGWindow("Connection Failed", "Remote connection failed, Please try again");
                //errorMsg.ShowDialog();
            }
        }

        private void drCarAgent_StateChanged(object sender, SessionStateChangedEventArgs e)
        {
            MessageBox.Show(e.SessionState.ToString());
        }

        private void chkPHR_Click(object sender, RoutedEventArgs e)
        {
            if (!SettingsPage.validPHRDb)
            {
                MSGWindow msgWindow = new MSGWindow(Messages.TTL_DBINVALID, Messages.MSG_DBINVALID_PHR);
                msgWindow.ShowDialog();
                chkPHR.IsChecked = false;
            }
            else
            {
                setStartBtnState();
                if (chkPHR.IsChecked == false)
                {
                    progPHR.Value = 0;
                    lblPHRPercent.Content = "";
                    lblStatus.Content = "";
                    spPHRProgress.Visibility = System.Windows.Visibility.Hidden;
                }
            }
        }

        private void chkDRCD_Click(object sender, RoutedEventArgs e)
        {
            if (!SettingsPage.validDCDRDb)
            {
                MSGWindow msgWindow = new MSGWindow(Messages.TTL_DBINVALID, Messages.MSG_DBINVALID_DCDR);
                msgWindow.ShowDialog();
                chkDRCD.IsChecked = false;
            }
            else
            {
                setStartBtnState();
                if (chkDRCD.IsChecked == false)
                {
                    progDRCD.Value = 0;
                    lblDRCDPercent.Content = "";
                    lblStatus.Content = "";
                    spDRCDProgress.Visibility = System.Windows.Visibility.Hidden;
                }
            }
        }

        private void setStartBtnState()
        {
            if (chkPHR.IsChecked == true || chkDRCD.IsChecked == true)
            {
                btnSyncStart.IsEnabled = true;
            }
            else
            {
                btnSyncStart.IsEnabled = false;
            }
        }


        public void drCarAgent_SessionProgress(object sender, SessionProgressEventArgs e)
        {
            Application.Current.Dispatcher.Invoke((Action)(() =>
            {
                lblStatus.Content = "DRS: "+e.SyncStage.ToString();
                progDRCD.Value = e.PercentCompleted;
                lblDRCDPercent.Content = e.PercentCompleted + "%";
                if (e.PercentCompleted == 100)
                {
                    lblStatus.Content = "DRS: Complete";
                }
                //else
                //{
                //    lblStatus.Content = "";
                //}
            }));
        }

        private void phrAgent_SessionProgress(object sender, SessionProgressEventArgs e)
        {
            Application.Current.Dispatcher.Invoke((Action)(() =>
            {
                lblStatus.Content = "PHR: "+e.SyncStage.ToString();
                progPHR.Value = e.PercentCompleted;
                lblPHRPercent.Content = e.PercentCompleted + "%";
                if (e.PercentCompleted == 100)
                {
                    lblStatus.Content = "PHR: Complete";
                }
                //else
                //{
                //    lblStatus.Content = "";
                //}
            }));
        }

        private void chkPHR_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = config.AppSettings.Settings;
            SettingsPage.validPHRDb = Convert.ToBoolean(settings[SyncKeys.VALIDPHRDB].Value);
            SettingsPage.validDCDRDb = Convert.ToBoolean(settings[SyncKeys.VALIDDCDRDB].Value);
            MainWindow.Instance.btn_home.Visibility = System.Windows.Visibility.Hidden;
            MainWindow.Instance.btn_settings.Visibility = System.Windows.Visibility.Visible;
            MainWindow.Instance.btn_add_organization.Visibility = System.Windows.Visibility.Hidden;
            MainWindow.Instance.btn_view_organization.Visibility = System.Windows.Visibility.Hidden;
            MainWindow.Instance.btn_logout.Visibility = System.Windows.Visibility.Visible;
            MainWindow.Instance.btn_changePassword.Visibility = System.Windows.Visibility.Visible;

            //loading database names
            if (SessionData.user.USERNAME == "axiohelix")
            {
                SyncKeys.PHRDBNAME = SyncKeys.PHRDBNAME_DEFAULT;
                SyncKeys.DCDRDBNAME = SyncKeys.DCDRDBNAME_DEFAULT;
            }
            else
            {
                SyncKeys.PHRDBNAME = SyncKeys.PHRDBNAME_DEFAULT + "_" + SessionData.organization.ID;
                SyncKeys.DCDRDBNAME = SyncKeys.DCDRDBNAME_DEFAULT + "_" + SessionData.organization.ID;
            }
            //SyncConnection.Instance.PHRDbPath = "";
            //SyncConnection.Instance.DCDRDbPath = "";

            //SyncConnection.updateConnectionStrings();
        }

        public void resetProgress()
        {
            Application.Current.Dispatcher.Invoke((Action)(() =>
            {
                progPHR.Value = 0;
                lblPHRPercent.Content = "";
                spPHRProgress.Visibility = System.Windows.Visibility.Hidden;
                progDRCD.Value = 0;
                lblDRCDPercent.Content = "";
                spDRCDProgress.Visibility = System.Windows.Visibility.Hidden;
                chkPHR.IsChecked = false;
                chkDRCD.IsChecked = false;
                btnSyncStart.IsEnabled = false;
                lblStatus.Content = "";
            }));
        }
    }
}
